#!/usr/bin/python

import os
import time
import fnmatch

def walk_matching_filenames(pattern, root=os.curdir):
    """Generator for walking root directory matching pattern 
           against filenames
    """
    for path, dirs, files in os.walk(os.path.abspath(root)):
        for filename in fnmatch.filter(files, pattern):
            yield os.path.join(path, filename)

def listdir_files(root=os.curdir):
    """Generator for listing files (not directories or links)
    """
    files = os.listdir(os.path.abspath(root))
    for item in files:
       output = os.path.join(root, item)
       if os.path.isfile(output):
          yield output
           
def listdir_files_matching_filenames(pattern, root=os.curdir):
    """Generator for listing files (not directories or links)
       and filtering filenames
    """
    files = fnmatch.filter(listdir_files(root), pattern)
    for item in files:
        (head, tail) = item.split('.')
        yield head

def mkdir(newdir):
    """Works the way a good mkdir should :)
           - already exists, silently complete
           - regular file in the way, raise an exception
           - parent directory(ies) does not exist, make them as well
       Note that I find this function without any author information	
    """
    if os.path.isdir(newdir):
        pass
    elif os.path.isfile(newdir):
        raise OSError("a file with the same name as the desired " \
                      "dir, '%s', already exists." % newdir)
    else:
        head, tail = os.path.split(newdir)
        if head and not os.path.isdir(head):
            os.mkdir(head)
        if tail:
            os.mkdir(newdir)

import shutil

def clean_copy_dir(source, target):
    """make a clean copy of directories tree, from source to target
    """
    if os.path.exists(target):
       shutil.rmtree(target)

    shutil.copytree(source, target)


def execute_backup(source, target_dir, comment):
	"""
	1. The files and directories to be backed up are specified in a list.
		source = ['/home/user/documents/work', '/home/user/documents/local_things']
		If you are using Windows, use source = [r'C:\Documents', r'D:\Work'] or something like that
	2. The backup must be stored in a main backup directory. For example
		target_dir = '/home/user/backup/' 
	3. The files are backed up into a compressed file.
	4. The current day is the name of the subdirectory in the main directory
	5. The current time is the name of the compressed archive
	6. Take a short comment to create the name of the compressed file
	"""
	
	# The current day is the name of the subdirectory in the main directory
	today = target_dir + time.strftime('%Y%m%d')
	# The current time is the name of the compressed archive
	now = time.strftime('%H%M%S')
	
	# Check if a comment was entered
	if len(comment) == 0: 
	   target = today + os.sep + now + '.tar'
	else:
	# Notice the backslash!	
	   target = today + os.sep + now + '_' + \
		comment.replace(' ', '_') + '.tar'
	
	# Create the subdirectory if it isn't already there
	if not os.path.exists(today):
		os.mkdir(today) # make directory
	
	# 5. We use the tar command (in Unix/Linux) to put the files in a tar.gz archive
	tar_command = 'tar -cvzf %s %s' % (target, ' '.join(source))
	print 'tar command ', tar_command
	
	# Run the backup
	if os.system(tar_command) == 0:
	   return '%s: backup ok' % target
	else:
	   return '%s: backup error' % target


